﻿using SocialCee.Authorization;
using SocialCee.Authorization.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Http.Filters;
using System.Web.Security;
using System.Net.Http;

namespace SocialCee.WebApi.Filters
{

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class CustomRoleAttribte : AuthorizationFilterAttribute
    {
        public ERoles[] RoleSet { get; set; }
        public override bool AllowMultiple
        {
            get
            {
                return true;
            }
        }

        /// <summary>
        /// Check if user is in role
        /// </summary>
        /// <param name="actionContext"></param>
        public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            if (Thread.CurrentPrincipal.Identity.IsAuthenticated)
            {
                var authHeader = actionContext.Request.Headers.Authorization;

                if (authHeader != null)
                {
                    if (authHeader.Scheme.Equals("basic", StringComparison.OrdinalIgnoreCase) &&
                        !String.IsNullOrWhiteSpace(authHeader.Parameter))
                    {
                        var credArray = GetCredentials(authHeader);
                        var userName = credArray[0];
                        var password = credArray[1];

                        bool isInRole = false;
                        foreach (ERoles role in RoleSet)
                        {
                            if (RoleManager.IsInRole(userName, role.ToString()))
                            {
                                isInRole = true;
                                break;
                            }
                        }

                        if (isInRole)
                            return;
                        else
                            HandleUnauthorizedRequest(actionContext);
                    }
                }
            }

            HandleUnauthorizedRequest(actionContext);
        }

        /// <summary>
        /// Get user details
        /// </summary>
        /// <param name="authHeader"></param>
        /// <returns></returns>
        private string[] GetCredentials(System.Net.Http.Headers.AuthenticationHeaderValue authHeader)
        {

            //Base 64 encoded string
            var rawCred = authHeader.Parameter;
            var encoding = Encoding.UTF8;
            var cred = encoding.GetString(Convert.FromBase64String(rawCred));

            var credArray = cred.Split(':');

            return credArray;
        }

        /// <summary>
        /// Http 401 error
        /// </summary>
        /// <param name="actionContext"></param>
        private void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);

        }
    }
}